use std::error::Error;
use std::time;
use anyhow::{Result, anyhow};
use headless_chrome::{Browser, LaunchOptionsBuilder};
use headless_chrome::protocol::cdp::Page;
use std::thread;
use super::ocr::ocr_captcha;

pub fn browser() -> Result<Browser> {
  let opt = LaunchOptionsBuilder::default()
      .headless(false)
      .window_size(Some((1920, 1080)))
      .idle_browser_timeout(time::Duration::from_millis(60_000)) // <- This
      .build()
      .map_err(|e| anyhow!(e))?;
  let browser = Browser::new(opt).map_err(|e| anyhow!(e));
  browser
}
const SLEEP_MILLIS:u64 = 100;

pub fn browse_wikipedia() -> Result<(), Box<dyn Error>> {
    let browser = browser()?;

    let tab = browser.wait_for_initial_tab()?;

    // Navigate to wikipedia
    tab.navigate_to("http://y.162lh.com/dh/enter")?;

    // Wait for network/javascript/dom to make the search-box available
    // and click it.
    tab.wait_for_element("input#userId")?.focus()?;
    // Type in a query and press `Enter`
    tab.type_str("zcxx001")?;

    thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));

    tab.wait_for_element("input#password")?.click()?;
    tab.type_str("229203")?;


    let mut _png_data = tab
        .wait_for_element("#numimg")?
        .capture_screenshot(Page::CaptureScreenshotFormatOption::Jpeg)?;

    let output = ocr_captcha(&mut _png_data);
    let output = output.replace("\n", "");
    println!("output=>{}", output);
    
    tab.wait_for_element("input#inputRandValue")?.click()?;
    tab.type_str(&*output)?;

    thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));
    tab.wait_for_element("input[type='checkbox']")?.click()?;

    thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));
    tab.wait_for_element("button[type='submit']")?.click()?;

    println!("click button for login!");
    
    // thread::sleep(time::Duration::from_millis(5000));
    // // We should end up on the WebKit-page once navigated
    let frame = tab.wait_for_element("#framePage")?;
    assert!(tab.get_url().ends_with("/dh/frame2.html"));

    let attrs = frame.get_attributes().unwrap().unwrap();
    println!("attr=>{:?}!", attrs);
  //   if let Some(attr_map) = attrs {
  //     let href = attr_map.get("src").unwrap();  // <-- here is the key
      
  // }
    // let tab = browser.new_tab()?;
    tab.navigate_to("http://y.162lh.com/dh/frame.html")?;


    // thread::sleep(time::Duration::from_millis(3000));

    println!("redirect to home success!");
    
    tab.wait_for_element("#app")?;
    println!("reach to iframe inner!");

    let li = tab.wait_for_element("#sidebar-menu > li:nth-child(4)")?;
    println!("find menu!");
    li.click()?;

    thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));

    tab.navigate_to("http://y.162lh.com/dh/view?_vid=8CF4DAA0F552CCFF46540E08F219C464&menuId=99.04.01&shdc=0.34658796406474557")?;
    
    thread::sleep(time::Duration::from_millis(SLEEP_MILLIS * 500));
    // // Take a screenshot of the entire browser window
    // let _jpeg_data = tab.capture_screenshot(
    //     Page::CaptureScreenshotFormatOption::Jpeg,
    //     None,
    //     None,
    //     true)?;

    // // Take a screenshot of just the WebKit-Infobox
    // let _png_data = tab
    //     .wait_for_element("#mw-content-text > div > table.infobox.vevent")?
    //     .capture_screenshot(Page::CaptureScreenshotFormatOption::Png)?;

    // // Run JavaScript in the page
    // let remote_object = elem.call_js_fn(r#"
    //     function getIdTwice () {
    //         // `this` is always the element that you called `call_js_fn` on
    //         const id = this.id;
    //         return id + id;
    //     }
    // "#, vec![], false)?;
    // match remote_object.value {
    //     Some(returned_string) => {
    //         dbg!(&returned_string);
    //         assert_eq!(returned_string, "firstHeadingfirstHeading".to_string());
    //     }
    //     _ => unreachable!()
    // };

    Ok(())
}

